﻿namespace com.crownpack
{
    using com.crownpack.InitiativesDao;

    using Microsoft.SharePoint;

    /// <summary>
    /// List Item Events
    /// </summary>
    public class InitiativesItemEventReceiver : SPItemEventReceiver
    {
        #region Methods

        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded( SPItemEventProperties properties )
        {
            EventFiringEnabled = false;

            Initiative initiative = new Initiative( properties.ListItem , SPEventType.Add);
            initiative.SystemUpdate( );

            upsertItemInMaster( properties );

            EventFiringEnabled = true;
        }

        /// <summary>
        /// An item is being deleted.
        /// </summary>
        /// <param name="properties"></param>
        public override void ItemDeleting( SPItemEventProperties properties )
        {
            EventFiringEnabled = false;

            deleteItemFromMaster( properties );

            EventFiringEnabled = true;
        }

        /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemUpdated( SPItemEventProperties properties )
        {
            EventFiringEnabled = false;

            Initiative initiative = new Initiative( properties.ListItem, SPEventType.Modify );
            initiative.SystemUpdate( );

            upsertItemInMaster( properties );

            EventFiringEnabled = true;
        }

        void deleteItemFromMaster( SPItemEventProperties properties )
        {
            InitiativesMasterDao dao = new InitiativesMasterDao( properties.WebUrl );
            dao.Delete( properties.ListItem );
        }

        void upsertItemInMaster( SPItemEventProperties properties )
        {
            if ( properties.ListItem.Title.Trim( ).Equals( string.Empty ) )
                return;
            InitiativesMasterDao dao = new InitiativesMasterDao( properties.WebUrl );
            dao.Upsert( properties.ListItem );
        }

        #endregion Methods
    }
}